/*
 * @Description: 权限
 * @Author: jxy
 * @Date: 2021-7-14 09:12:46
 * @LastEditors: jxy
 * @LastEditTime: 2021-07-14 15:36:01
 */

// import { useI18n } from 'vue-i18n'
import router from './router'
import { RouteLocationNormalized } from 'vue-router'
import { useUserStore } from './store/user'
import { useLoginStore } from './store/login'
import { getToken, setToken_Code, getToken_Code,setToken_AccToken,getToken_AccToken,setToken_Name,getToken_Name, getToken_Uid, setCodeToken } from './utils/cookies'
import { GetNewInfo } from './api/sys/userCode';
import Cookies from 'js-cookie'

// import { GetPermCode } from '@/api/sys/user';
// import settings from '@/config/default/setting.config'
//配置信息
const docking = {
  appId: "hwyxgl",
  url:"http://10.81.106.123",
}
const timer = null;


router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: any) => {
  const LoginStore = useLoginStore();

  let acctoken = getToken_AccToken();
  let uid = getToken_Uid();
  
  //每次请求一下用户，看token是否过期
  if (acctoken != undefined && acctoken != "" && acctoken != "undefined" ) {
    LoginStore.login_name_fn({ access_token: acctoken, uid: uid }).then((res) => {
      let loginName = res.loginName;
      if (loginName == "" || loginName == undefined || loginName == "undefined") {
        localStorage.setItem("JWT", "");
        LoginStore.setLoginName("");
        LoginStore.setLoginAccToken("");
        LoginStore.setLoginUid("");
        LoginStore.setLoginCode("");
        location.reload();
        
      }
    })
    
  }

  next();

})
//设置一分钟失效，模拟token失效
// setTimeout(function () {
//   localStorage.setItem("JWT", "");
//   const LoginStore = useLoginStore();
//   LoginStore.setLoginName("");
//   LoginStore.setLoginAccToken("");
//   LoginStore.setLoginUid("");
//   LoginStore.setLoginCode("");
//   location.reload();
// }, 1 * 60 * 1000)


router.afterEach((to: RouteLocationNormalized) => {
  const useStore = useUserStore()
  const LoginStore = useLoginStore()
   //新code值
  let newcode = getToken_Code();
  let accToken = getToken_AccToken();
  console.log(newcode);
  console.log(getToken_Code());
  
  if ((newcode != "" && newcode != undefined && newcode != "undefined")) {
    
    if (accToken == "" || accToken == undefined || accToken == "undefined") {
      LoginStore.login_Acctoken_fn(newcode).then((res) => {
        let name = getToken_Name();
        if (name != "" && name != undefined && name != "undefined") {
          useStore.getJwt({ username: name }).then((res) => {
            location.reload();
          })
        }
      })
    } else {
      let jwt = localStorage.getItem("JWT");
      if (jwt == "" && jwt == undefined && jwt == "undefined") {
        let name = getToken_Name();
        useStore.getJwt({ username: name }).then((res) => {
          location.reload();
        })
      }
    }
    
  } else {
     
     let new_href = location.href;
     if (new_href && new_href.indexOf("code") != -1) {
  
      let str = new_href.split("?");
       newcode = str[1].substring(5, str[1].indexOf('&'));
      setToken_Code(newcode);
        if (accToken == "" || accToken == undefined || accToken == "undefined") {
          //根据code获取token和name
          LoginStore.login_Acctoken_fn(newcode).then((res) => {
             //设置token
            accToken = getToken_AccToken();
         
            if (accToken == "" || accToken == "undefined" || accToken == undefined) {
              
            } else {
              let name = getToken_Name();
              if (name != "" && name != "undefined" && name != undefined) {
                let jwt = localStorage.getItem('JWT');
                //jwt等于空的时候需要根据name重新获取jwt
                if (jwt == "" || jwt == undefined || jwt == "undefined") {
                  useStore.getJwt({ username: name }).then((res) => {
                    location.reload();
                  });
                }
              }
            
            }
         
          })
         
        }
      
     } else {
       let url = location.href;
       let s2 = localStorage.getItem("s2");
       let w = window.open(docking.url+"/idp/oauth2/authorize?redirect_uri=" + url.replace("#", "%23") + "&state=123&client_id="+docking.appId+"&response_type=code", "bbb",
          "height=-10,width=-10,top=2000,left=-200,resizable=yes;status:no,help:no;z-look:no");
       
      //  let timer = localStorage.get("timer2");
      //  if (timer != undefined && timer != null && timer != '') {
      //    window.clearInterval(Number(timer));
      //  }

         let timer2 = window.setInterval(() => {
           let timer = localStorage.getItem("timer2");
           let jwt = localStorage.getItem('JWT');
           //防止死循环
           let status = localStorage.getItem('status');
           if (status == null) {
             status = "";
             localStorage.setItem("status", status);
           } else if (status.length > 10) {
             localStorage.removeItem("status");
             window.clearInterval(timer);
             localStorage.setItem("timer2","");
           } else {
             status += "a";
             localStorage.setItem("status", "");
           }
           if (jwt != '' && jwt != undefined && jwt != 'undefined') {
             window.clearInterval(timer);
             localStorage.setItem("timer2","");
             localStorage.removeItem("status");
             if (w != null) {
               w.close();
             }
             //debugger;
             location.reload();
           }
         }, 1000);
        localStorage.setItem("timer2",timer2+"");
       
    }
    
  }
  
})

